import type { LocationQueryRaw, Router } from 'vue-router'
import { isNavigationFailure } from 'vue-router'
import { useLoginStore } from '@/stores/loginStore'

/**
 * 通用守卫配置
 * @param router
 */
function setupCommonGuard(router: Router) {
  router.beforeEach(() => {
    ElMessage.closeAll()
  })
  router.afterEach(async (_to, _, failure) => {
    if (isNavigationFailure(failure)) {
      // eslint-disable-next-line no-console
      console.log('failed navigation', failure)
    }
  })
}

function setupAccessGuard(router: Router) {
  router.beforeEach(async (to, from, next) => {
    if (to.name === 'login' || to.name === 'codeCallback' || to.path === from.path) {
      next()
      return
    }
    const loginStore = useLoginStore()
    if (loginStore.isLogin()) {
      try {
        await loginStore.loadLoginInfo()
        await loginStore.loadMenus()
        const path = to.matched[to.matched.length - 1].path
        loginStore.activeMenu(path)// 激活菜单
        next()
      }
      catch (e: any) {
        if (e.errCode === 401) {
          await loginStore.logout()
          next({
            name: 'login',
            query: {
              redirect: to.path,
            } as LocationQueryRaw,
          })
        }
      }
    }
    else {
      next({
        name: 'login',
        query: {
          redirect: to.path,
        } as LocationQueryRaw,
      })
    }
  })
}

/**
 * 项目守卫配置
 * @param router
 */
function createRouterGuard(router: Router) {
  /** 通用 */
  setupCommonGuard(router)
  /** 权限访问 */
  setupAccessGuard(router)
}

export { createRouterGuard }
